package com.atguigu.auth.controller;
import com.atguigu.auth.service.SysMenuService;
import com.atguigu.auth.service.SysUserService;
import com.atguigu.common.config.exception.GuiguException;
import com.atguigu.common.config.jwt.JwtHelper;
import com.atguigu.common.result.MD5;
import com.atguigu.common.result.Result;
import com.atguigu.model.system.SysUser;
import com.atguigu.vo.system.LoginVo;
import com.atguigu.vo.system.RouterVo;
import com.atguigu.vo.system.SysUserQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mysql.cj.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/admin/system/sysUser")
@Api(tags = "用户管理接口")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysMenuService sysMenuService;

    @GetMapping("{page}/{limit}")
    public Result pageUser(@PathVariable Long page,
                           @PathVariable Long limit,
                           SysUserQueryVo sysUserQueryVo){

        Page<SysUser> sysUserPage = new Page<SysUser>();
        //2.封装条件，判断条件不为空
        LambdaQueryWrapper<SysUser> sysUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        String username = sysUserQueryVo.getKeyword();
        String createTimeBegin = sysUserQueryVo.getCreateTimeBegin();
        String createTimeEnd = sysUserQueryVo.getCreateTimeEnd();
        //判断条件值
        if(!StringUtils.isNullOrEmpty(username)){
            sysUserLambdaQueryWrapper.like(SysUser::getUsername,username);
        }
        //大于等于开始时间
        if(!StringUtils.isNullOrEmpty(createTimeBegin)){
            sysUserLambdaQueryWrapper.ge(SysUser::getCreateTime,createTimeBegin);
        }
        //小于等于结束时间
        if(!StringUtils.isNullOrEmpty(createTimeEnd)){
            sysUserLambdaQueryWrapper.le(SysUser::getDescription,createTimeEnd);
        }

        //调用分页方法
        IPage<SysUser> pageModel = sysUserService.page(sysUserPage, sysUserLambdaQueryWrapper);
//        System.out.println("user================="+pageModel.getTotal());
        return Result.ok(pageModel);
    }



    @ApiOperation(value="获取用户")
    @GetMapping("get/{id}")
    public Result get(@PathVariable Long id) {
        SysUser user = sysUserService.getById(id);
        return Result.ok(user);
    }


    @ApiOperation(value="删除用户")
    @DeleteMapping("remove/{id}")
    public Result deleteByid(@PathVariable Long id) {
         sysUserService.removeById(id);
        return Result.ok();
    }

    @ApiOperation(value = "新增用户")
    @PostMapping("save")
    public Result save(@RequestBody SysUser user) {
        sysUserService.save(user);
        return Result.ok();
    }


    @ApiOperation(value = "修改用户")
    @PutMapping("update")
    public Result update(@RequestBody SysUser user) {
         sysUserService.updateById(user);
        return Result.ok();
    }

   // http://localhost:9528/dev-api/vue-admin-template/user/login
//   {"code":20000,"data":{"token":"admin-token"}}
    @PostMapping("/login")
    public Result login(@RequestBody LoginVo loginVo){
//        Map<String, Object> map = new HashMap<>();
//        map.put("token","admin-token");
//        return  Result.ok(map);

        //1. 获取输入用户名和密码
        String username = loginVo.getUsername();
        String password = loginVo.getPassword();
        //2. 根据用户名查询数据库
        LambdaQueryWrapper<SysUser> userWq = new LambdaQueryWrapper<>();
        userWq.eq(SysUser::getUsername,username);
        //根据用户名查询出一个条件
        SysUser sysUser = sysUserService.getOne(userWq);
        //3 用户信息是否存在
        if (sysUser == null){
            throw new GuiguException(201,"用户不存在的");
        }
        //4 判断密码
        //4.1 数据库中查询出来的密码
        String password1 = sysUser.getPassword();
        //4.2 输入的密码进行MD5加密
        String encrypt = MD5.encrypt(password);
        if (!password1.equals(encrypt)){
            throw new GuiguException(201,"密码不正确");
        }
        //5 判断用户是否被禁用 1:可用 0：禁用
        if (sysUser.getStatus().intValue() == 0){
            throw new GuiguException(201,"用户被禁用,请联系管理员");
        }

        //6.根据jwt的用户id和用户名生成token字符串
        String token = JwtHelper.createToken(sysUser.getId(), sysUser.getUsername());
        //7.结果返回
        Map<String,Object> map = new HashMap<>();
        map.put("token",token);
        return Result.ok(map);
    }


    //http://localhost:9528/dev-api/vue-admin-template/user/info?token=admin-token
    /**
     * {
     *     "code": 20000,
     *     "data": {
     *         "roles": [
     *             "admin"
     *         ],
     *         "introduction": "I am a super administrator",
     *         "avatar": "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
     *         "name": "Super Admin"
     *     }
     * }
     * @return
     */
    @GetMapping("/info")
    public Result info(HttpServletRequest request){
        System.out.println("======info=================");
        // 需要返回数据格式
        // {"code":200,"data":{"roles":["admin"],"introduction":"I am a super administrator",
        // "avatar":"https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif","name":"Super Admin"}}

        // 1 从请求头获取用户信息（获取请求头token字符串）
        // 需要在前端设置（登录时把token放在请求头中）
        String token = request.getHeader("token");

        System.out.println("token==============");
        System.out.println(token);
        // 2 从token字符串获取用户ID和用户名称
//        Long userId = 1L; //JwtHelper.getUserId(token);
        Long userId = JwtHelper.getUserId(token);
        String username = JwtHelper.getUsername(token);

        // 3 根据用户ID查询数据库 把对应的用户查询出来
        SysUser sysUser = sysUserService.getById(userId);

        // 4 根据用户ID获取用户可以操作的菜单列表（前端的路由不能写死啦）
        // 用户角色关系表 角色菜单关系表 菜单表
        // 查询数据库动态构造路由
        List<RouterVo> routerVoList =  sysMenuService.findUserMenuListByUserId(userId);

        // 5 根据用户ID获取用户可以操作的按钮权限列表  perms（按钮权限） 是 permissions的简写
        // 返回的是 bnt.sysUser.list
        List<String> permsList = sysMenuService.findUserPermsByUserId(userId);

        // 6 返回的数据：t odo:表示需要完善的地方
        Map<String, Object> map = new HashMap<>();
        map.put("roles","[admin]");
        // 返回的是name 不是username
        map.put("name",sysUser.getName());
        map.put("avatar","https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        //返回用户可以操作的按钮
        map.put("buttons",permsList);
        // 返回用户可以操作的菜单
        map.put("routers",routerVoList);
        return  Result.ok(map);
    }


    @PostMapping("logout")
    public Result logout(){
        return Result.ok();
    }


//    /admin/system/sysUser/updateStatus/14/0

    @GetMapping("updateStatus/{id}/{status}")
    public Result updateStatus(@PathVariable Long id,@PathVariable Integer status){
        sysUserService.updateStatus(id,status);
        return Result.ok();
    }
}
